Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(consensus): node stalled after client has stopped #1001

Merged
merged 4 commits into from
Dec 11, 2024

Conversation

lklimek
Copy link
Collaborator

@lklimek lklimek commented Dec 11, 2024

Issue being fixed or feature implemented

Tenderdash does not recover after ABCI client errors and stops.

What was done?

Added proper error handling to panic on stopped client.
This causes restart of Tenderdash Docker container, reconnecting the client.

How Has This Been Tested?

Added unit test

Breaking Changes

None

Checklist:

  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have added or updated relevant unit/integration/functional/e2e tests
  • I have made corresponding changes to the documentation

For repository code-owners and collaborators only

  • I have assigned this pull request to a milestone

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Introduced a new error variable, ErrClientStopped, for improved error reporting.
  • Bug Fixes

    • Enhanced error handling in the commit verification process, now triggering a panic for specific error conditions.
  • Tests

    • Added a new test to verify panic behavior on client errors.
    • Updated existing tests for more comprehensive checks and clarity.
  • Documentation

    • Comments updated for clarity regarding error implications and verification processes.

@lklimek lklimek added this to the v1.3 milestone Dec 11, 2024
Copy link
Contributor

coderabbitai bot commented Dec 11, 2024

Walkthrough

The changes in this pull request introduce a new error variable, ErrClientStopped, in the socketClient struct to replace a hardcoded error message in the doRequest method, enhancing error handling consistency. Additionally, the TryAddCommitAction class in the state_try_add_commit.go file is updated to include a panic mechanism when encountering the ErrClientStopped error, altering the control flow to introduce a non-recoverable error condition. Minor formatting and comment adjustments are also made for clarity, but no significant logic changes occur.

Changes

File Path Change Summary
abci/client/socket_client.go Introduced ErrClientStopped variable; replaced hardcoded error message in doRequest method. Minor comment adjustments.
internal/consensus/state_try_add_commit.go Added import for errors package; updated verifyCommit method to panic on ErrClientStopped. Refined comments for clarity.
internal/consensus/state_test.go Added TestStateTryAddCommitPanicsOnClientError test; updated existing tests for timestamp matching and clarity.

Possibly related PRs

Suggested reviewers

  • QuantumExplorer
  • shumkov

🐇 In the code we hop and play,
With errors caught in a new way.
A client stops, we now can see,
A panic here, for clarity!
So let’s rejoice, with code so neat,
Our changes make the logic sweet!
🐰


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Experiment)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (1)
abci/client/socket_client.go (1)

41-44: Document the ErrClientStopped error variable for clarity.

The addition of the exported variable ErrClientStopped improves error handling consistency. To enhance code readability and maintainability, consider adding a documentation comment explaining the purpose and usage of ErrClientStopped.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7681ea4 and 0896537.

📒 Files selected for processing (2)
  • abci/client/socket_client.go (2 hunks)
  • internal/consensus/state_try_add_commit.go (2 hunks)
🔇 Additional comments (1)
abci/client/socket_client.go (1)

241-241: Verify consistency of error handling with ErrClientStopped.

By returning ErrClientStopped instead of a new error instance, ensure that all error comparisons in the codebase use errors.Is or errors.As to handle this error. Direct comparisons using == with error variables may fail due to different error instances.

To confirm consistent error handling, run the following script:

✅ Verification successful

Error handling for ErrClientStopped is consistent with Go best practices

The error is correctly defined as a package-level variable and returned directly without wrapping. Since there are no direct equality comparisons (==) found in the codebase and the error is returned as-is, the current implementation follows Go's error handling best practices. No changes are needed.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for locations where the "client has stopped" error is handled.

# Find all Go files except tests
FILES=$(fd --type f --extension go --exclude '*_test.go')

# Search for direct equality comparisons with error strings
rg -F 'err == "client has stopped"' $FILES

# Search for error comparisons with ErrClientStopped
rg -F 'err == ErrClientStopped' $FILES

# Search for error handling using errors.Is with ErrClientStopped
rg -F 'errors.Is(err, ErrClientStopped)' $FILES

Length of output: 64720


Script:

#!/bin/bash
# Let's search for ErrClientStopped definition and usage patterns

# Find where ErrClientStopped is defined
rg -l "ErrClientStopped.*=.*" 

# Search for error handling patterns with ErrClientStopped
rg -A 2 "if.*err.*{" | rg -B 2 "ErrClientStopped"

# Search for error returns with ErrClientStopped
rg "return.*ErrClientStopped"

# Search for error wrapping with ErrClientStopped
rg "fmt.Errorf.*ErrClientStopped"

Length of output: 322


Script:

#!/bin/bash
# Let's examine the ErrClientStopped definition and its usage context

# Show the error definition and surrounding context
rg -B 5 -A 5 "ErrClientStopped.*=.*" abci/client/socket_client.go

# Show all functions that return or use ErrClientStopped
rg -B 10 -A 2 "ErrClientStopped" abci/client/socket_client.go

# Look for any error handling patterns in test files
rg "ErrClientStopped" abci/client/*_test.go

Length of output: 1103

internal/consensus/state_try_add_commit.go Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (2)
internal/consensus/state_test.go (2)

3286-3286: Unnecessary use of t.Helper() in the test function

The t.Helper() method is intended to be used within helper functions to mark them as helpers. Calling it directly within the test function TestStateTryAddCommitPanicsOnClientError is unnecessary.

Apply this diff to remove the unnecessary call:

-	t.Helper()

3350-3352: Verify the panic message to ensure correct behavior

Currently, the test checks for any panic but does not verify if it's the expected one. To ensure the test is validating the correct panic scenario, consider checking the panic value.

Apply this diff to verify the panic message:

-	assert.Panics(t, func() {
+	assert.PanicsWithValue(t, abciclient.ErrClientStopped, func() {
 		_ = consensusState.ctrl.Dispatch(ctx, &TryAddCommitEvent{Commit: commit, PeerID: peerID}, &stateData)
 	})
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0896537 and 8b6f737.

📒 Files selected for processing (1)
  • internal/consensus/state_test.go (3 hunks)

internal/consensus/state_test.go Outdated Show resolved Hide resolved
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Outside diff range and nitpick comments (3)
internal/consensus/state_test.go (3)

3278-3354: LGTM! Well structured test for ABCI client error handling

The test effectively verifies that the consensus state panics when encountering an ABCI client error during block processing. The test setup and assertions are clear and comprehensive.

A few suggestions for improvement:

  1. Consider adding cleanup of mocks in a defer statement
  2. The error message assertion could be extracted to a constant for reuse
  3. Consider adding a test case for other ABCI methods like PrepareProposal
 func TestStateTryAddCommitPanicsOnClientError(t *testing.T) {
+    const expectedError = "ABCI client stopped, Tenderdash needs to be restarted: ProcessProposal abci method: client has stopped"
     ctx, cancel := context.WithCancel(context.Background())
     defer cancel()
+    defer func() {
+        app.AssertExpectations(t)
+    }()
     // ... rest of the test
     assert.PanicsWithError(t,
-        "ABCI client stopped, Tenderdash needs to be restarted: ProcessProposal abci method: client has stopped",
+        expectedError,
         func() {

3294-3299: Consider enhancing mock error handling

The mock configuration is good but could be enhanced:

  1. Add verification that ProcessProposal was actually called
  2. Consider testing with different error types beyond ErrClientStopped
 app := clientmocks.NewClient(t)
+app.On("ProcessProposal", mock.Anything, mock.Anything).
-    Return(&abci.ResponseProcessProposal{}, abciclient.ErrClientStopped).
-    Once()
+    Run(func(args mock.Arguments) {
+        // Verify the arguments
+        req := args.Get(1).(*abci.RequestProcessProposal)
+        assert.NotNil(t, req)
+    }).
+    Return(&abci.ResponseProcessProposal{}, abciclient.ErrClientStopped).
+    Once()

3309-3323: Consider adding more block validation checks

The block creation and commit handling is solid, but could benefit from additional validation:

  1. Validate block metadata matches expected values
  2. Add explicit checks for block parts
 block, err := sf.MakeBlock(state, 1, &types.Commit{}, kvstore.ProtocolVersion)
 require.NoError(t, err)
 require.NotZero(t, block.Version.App)
+require.Equal(t, state.LastBlockHeight+1, block.Height)
+require.NotEmpty(t, block.LastBlockID)
 block.CoreChainLockedHeight = 1

 commit, err := factory.MakeCommit(
     ctx,
     block.BlockID(nil),
     block.Height,
     0,
     stateData.Votes.Precommits(0),
     state.Validators,
     privVals,
 )
 require.NoError(t, err)
+require.Equal(t, block.Height, commit.Height)
+require.True(t, commit.BlockID.Equals(block.BlockID(nil)))
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 8b6f737 and b1c915d.

📒 Files selected for processing (2)
  • abci/client/socket_client.go (2 hunks)
  • internal/consensus/state_test.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • abci/client/socket_client.go

@lklimek lklimek enabled auto-merge (squash) December 11, 2024 11:11
@lklimek lklimek merged commit a740370 into v1.3-dev Dec 11, 2024
16 checks passed
@lklimek lklimek deleted the fix/stall-on-client-stopped branch December 11, 2024 11:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants